package com.site.common.filter.handler;

import com.site.common.annotation.Login;
import com.site.common.exception.BusinessException;
import com.site.common.filter.AbstractBaseFilter;
import com.site.util.JwtTokenUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * login 过滤器
 */
@Component
public class LoginFilter extends AbstractBaseFilter<Boolean> {

    private static final String TOKEN = "Authorization";

    @Override
    protected Boolean execute(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, ApplicationContext context) {
        Login login = handlerMethod.getMethod().getAnnotation(Login.class);
        if (login.isLogin()){
            String token = request.getHeader(TOKEN);
            if (token == null){
                token = request.getParameter(TOKEN);
            }
            if (token == null || "".equals(token)){
                logger.warn("<<================= Authorization不存在!,请求地址:{}",request.getRequestURI());
                throw new BusinessException("Authorization不存在!");
            }
            if (!JwtTokenUtil.check(token)){
                logger.warn("<<================= Authorization不合法!,请求地址:{}",request.getRequestURI());
                throw new BusinessException("Authorization不合法!");
            }
            if (JwtTokenUtil.isTokenExpired(token)){
                logger.warn("<<================= Authorization无效!,请求地址:{}",request.getRequestURI());
                throw new BusinessException("Authorization无效!");
            }
        }
        if (login.required() || login.scope() > 0){
            // 根据实际需求进行验证
        }
        return false;
    }
}
